package com.bos.crm.domain;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 */

@Transactional
public  class CustomerServiceImp implements CustomerService {

    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Customer> findAll() {
        String sql = "select * from t_customer";
        List<Customer> customers = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Customer.class));
        return customers;
    }

    @Override
    public List<Customer> findNotAssociatedCustomer() {
        return jdbcTemplate.query(
                "select * from t_customer t where t.decidedzone_id is null", new BeanPropertyRowMapper(Customer.class));
    }

    @Override
    public List<Customer> findhasAssociatedCustomer() {
        return jdbcTemplate.query(
                "select * from t_customer t where t.decidedzone_id is not null", new BeanPropertyRowMapper(Customer.class));
    }

    @Override
    public void update(String decidedZoneId, Integer[] ids) {
        jdbcTemplate.update("update t_customer set decidedzone_id = null where decidedzone_id = ?",decidedZoneId);

        for (int i = 0; i < ids.length && ids[0] != -1; i++) {
            jdbcTemplate.update("update t_customer set  decidedzone_id = ? where id =?",decidedZoneId,ids[i]);
        }
    }

    @Override
    public List<Customer> findByDecidedZoneId(String id) {
        List customers = jdbcTemplate.query("select * from t_customer where decidedzone_id = ?", new String[]{id},
                new BeanPropertyRowMapper(Customer.class));
        return customers;
    }

    @Override
    public Customer findCustomerBytelephone(String telephone) {
        List customers = jdbcTemplate.query("select * from t_customer where telephone = ?", new String[]{telephone},
                new BeanPropertyRowMapper(Customer.class));
        return (Customer) customers.get(0);
    }

    @Override
    public String findDecidedZoneIDbyAddress(String address) {
        List customers = jdbcTemplate.query("select * from t_customer where address = ?", new String[]{address},
                new BeanPropertyRowMapper(Customer.class));
        if (customers != null && customers.size() != 0) {
            return ((Customer) customers.get(0)).getDecidedZone_Id();
        }else {
            return null;
        }
    }


    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
